import 'dart:async';

import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:text2audio/global.dart';
import 'package:text2audio/iconfont.dart';
import 'package:text2audio/toast.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '文本朗读器',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: '文本朗读器'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  AudioPlayer audioPlayer = AudioPlayer();
  // 音频总时间
  Duration duration;
  // 音频当前时间
  Duration position;
  // 音频是否正在播放
  bool complete = false;
  bool circlePlay = false;
  // 进度条进度值
  double sliderValue = 0;

  String originText = '';

  // 开始播放
  play() async {
    String url = getAudioUrl(originText);
    final result = await audioPlayer.play(url, position: position);
    audioPlayer.setPlaybackRate(playbackRate: 1.0);
    if (result == 1) {
      setState(() {
        complete = true;
      });
    }
  }

  // 暂停播放
  void pause() async {
    final result = await audioPlayer.pause();
    if (result == 1) {
      setState(() {
        complete = false;
      });
    }
  }

  void setSeek(seek) {
    audioPlayer.seek(seek);
  }

  String getAudioUrl(String text) {
    var ss = text.replaceAll(RegExp(r"\s+\b|\b\s"), "");
    return "https://api.oioweb.cn/api/tts.php?txt=${Uri.encodeComponent(ss)}";
  }

  @override
  void initState() {
    audioPlayer.onPlayerStateChanged.listen((state) {
      // 播放完毕
      if (state == AudioPlayerState.COMPLETED) {
        // // 重置时长及播放状态
        setState(() {
          position = Duration(milliseconds: 0);
          duration = Duration(milliseconds: 0);
          complete = false;
        });
        if (circlePlay) play();
      }
    });

    // 播放进度监听
    audioPlayer.onAudioPositionChanged.listen((Duration p) {
      setState(() {
        position = p;
      });
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          widget.title,
          style: TextStyle(
            color: Global.fontColor,
            fontSize: 14,
            fontWeight: FontWeight.bold,
          ),
        ),
        backgroundColor: Global.backgroundColor,
        brightness: Brightness.dark,
        elevation: 0,
      ),
      body: Container(
        color: Global.backgroundColor,
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Container(
              margin: EdgeInsets.all(15),
              padding: EdgeInsets.all(10),
              decoration: BoxDecoration(
                color: Global.fontColor.withOpacity(.03),
                border: Border.all(
                  color: Global.fontColor.withOpacity(.1),
                ),
                borderRadius: BorderRadius.circular(5),
              ),
              child: ConstrainedBox(
                constraints: BoxConstraints(
                  maxWidth: MediaQuery.of(context).size.width,
                ),
                child: TextField(
                  maxLines: 13,
                  style: TextStyle(
                    color: Global.fontColor,
                    fontSize: 20,
                  ),
                  decoration: InputDecoration.collapsed(
                    hintText: '请输入需要机器朗读的文本\n文本不超过200字',
                    hintStyle: TextStyle(
                      color: Global.fontSecondColor.withOpacity(0.5),
                      fontSize: 20,
                    ),
                  ),
                  onChanged: (text) {
                    setState(() {
                      originText = text;
                    });
                  },
                ),
              ),
            ),
            SizedBox(height: 10),
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                SizedBox(width: 25),
                Text(
                  '循环播放已${circlePlay ? "开启" : "关闭"}',
                  style: TextStyle(
                    color: Global.fontSecondColor,
                    fontSize: 16,
                  ),
                ),
              ],
            ),
            SizedBox(height: 20),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                RaisedButton.icon(
                  padding: EdgeInsets.fromLTRB(10, 5, 10, 5),
                  color: Global.primaryColor,
                  elevation: 5,
                  icon: Icon(
                    complete ? Icons.pause : Icons.play_arrow,
                    color: Global.fontSecondColor,
                    size: 28,
                  ),
                  label: Text(
                    complete ? '暂停朗读' : '朗读文字',
                    style: TextStyle(
                      color: Global.fontSecondColor,
                      fontSize: 24,
                    ),
                  ),
                  onPressed: () {
                    if (originText.length > 200) {
                      Toast.show(context, msg: '请输入200字以内文本', duration: 1);
                    } else if (originText.trim() == '') {
                      Toast.show(context, msg: '请输入文本后点击朗读', duration: 1);
                    } else {
                      setState(() {
                        complete ? pause() : play();
                      });
                    }
                  },
                ),
                RaisedButton.icon(
                  padding: EdgeInsets.fromLTRB(10, 5, 10, 5),
                  color: Global.primaryColor,
                  elevation: 5,
                  icon: Icon(
                    circlePlay ? IconFont.tongbu : IconFont.xunhuan,
                    color: Global.fontSecondColor,
                    size: 28,
                  ),
                  label: Text(
                    circlePlay ? '关闭循环' : '循环播放',
                    style: TextStyle(
                      color: Global.fontSecondColor,
                      fontSize: 24,
                    ),
                  ),
                  onPressed: () {
                    setState(() {
                      circlePlay = !circlePlay;
                    });
                  },
                ),
              ],
            )
          ],
        ),
      ),
    );
  }
}
